package com.example.yz.happywoker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.example.yz.happywoker.timeline.TimeLineView;
import com.example.yz.happywoker.util.OrderInfoUtil2_0;
import com.example.yz.happywoker.util.PayResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyOrder extends Activity implements View.OnClickListener {
    // TimeLineView mView2;
    private List<String> data;
    private TextView content, category, Mystatus, handleDate, address, reservice_phone;
    private LinearLayout lin_1, lin_2;
    private TimeLineView mView2;
    private Button finishWork_1;
    private ImageView suggestion_back;


    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016090900470438";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088102174810390";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "TEST";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCcDIC00YQU7JPfshzjW/GpzhNgwrMWpUWnSMqwKmV02RlrkBpBN3oZ8iAVusF1NR/xJBic/5m/UjzIWiZ3o3i8cHiNDWAdtSYeNoRioE4hy6mW/Bxz8w22NDDd4D6ThWIcWZPyYZzMTuV5vFH6yIPaDGWjmYk7e4UlpIAKD2CDzwkO1urBWqkhMmu2mHd/Q5yW6AlccGNGQqtEu0Pw2zCvb3PLFts22HC9702L8sMOgzQT/DDCtQBaDNGwX/OiKpKMVJhwJ0lOpYkXsgmRpUfirLstYgrcCrmGIPRNP+CMOzxNRDz3grDyJhKXKEJGn26DvPC1VuYZl3DW/l0Ca9cjAgMBAAECggEAHTHFno6YHGYKYE5tUyfvdWpFe9PRN4piFqLqsLyt0IeRVutVzh+360S+NfKDoQ74U+AB7tVvCTk0f/NFwRpHS1Hra9A1zDkI0Zw3dlAxbecxajrug87UIONwxQHgEy9gJJepsy4J7LtR+U1/NODwsgmhtlLSNtusFFfLUJaB4wa8YvNCTIlCgIbZXHVt6nTpOXR7XiBxS2iRm/MePW6jwUAwiy/gJlul8B9qtPDdGWQA7+fiZFDX4ybF9bvqkts0tajIN3hcYJwHziwFSrwVIoFkXBvqzqeRGAWMcoj1AtSJ8lAuBE7h/bGSbqw8WT0xGolrBMjkFevxm7D/nfyRGQKBgQDkT274cjoOxFPxkbl/+npULZd7/Umc+puOCRvxZIo8txkwiRa75+FciFi9KH7cXi+fKX841CdgBrkH3jJB4V6jcL+ff3gS/yG+lCvQ8pb/D8lc539HdyX3W6jMezOA0mcYxVehH6BqS+pk1XkMOrgtXw7GecdbpFFLvwy2rh7fVQKBgQCu+X/ZF15CLGasr6jRus3suR8CcxhWmEhHy3cFiLo+Mqy0+qBnq8GvQ1xrQf4Jgo6fC1W68ILOfVKN3b+Hejq/wapwV9Ynsh5p8XT8c9lRDw0RHSUJHmXGvz2/IWGCCO2zGXh4wYuUSX8tuFu8T4/Db2rBWiaQGXJVyp2VZYWslwKBgQDYitqWvEiCnwV7Npr5XknOM1vdVtQOFseZRNyC7LgMdCFpHm04leryx8NazeDdBFwomsQ200nxUw8F/mIuiCIp5JNrJQxvABsyVfjk+mHq0z9KZasbzk9tODt2jlfAFE+CeBHwGT4d85kCQFLKHZt4NROffftu2P/eVvso/Sb87QKBgBpFe9yslYp6ADCNb1uOIL0aTn2fqlfWJYQiGIzMKqqMEUJbHxpxv3MBOi8giXQEFkXq/cRDuGAokOycDtXYlFmWSnDzv0PWipp9loMRId/50oxvQ9BKsB1XOX4pFOrhTE9H077N0JdDMcU7mQp9J6jAYdcGIiQgrfoTofV8eMWhAoGBAKsVZ07lq593R+Rto2HOEp1xa+Mf3Cp+TCJL88Vc50GcwgJQPOabqThaZ6x+oG+ZcGl/dEu8mxAKQaEH/Jm0C2FuXyz74K1+B1s947JheMb6ZOUSqv0R7jNpWnxuBzbjUVMeIo0iI/7pMwW6WLljzTOfSxzHwz7XNjzd66VB+kwf";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {

                        ChangeOrderState();
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(MyOrder.this, "支付成功", Toast.LENGTH_SHORT).show();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(MyOrder.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
//                case SDK_AUTH_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
//                    String resultStatus = authResult.getResultStatus();
//
//                    // 判断resultStatus 为“9000”且result_code
//                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
//                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
//                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
//                    } else {
//                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
//
//                    }
//                    break;
//                }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        init();
        getinfo();
    }

    private void init() {
        lin_1 = (LinearLayout) findViewById(R.id.lin_1);
        lin_2 = (LinearLayout) findViewById(R.id.lin_2);
        mView2 = (TimeLineView) findViewById(R.id.timeLineView2);
        lin_1.setVisibility(View.INVISIBLE);
        mView2.setVisibility(View.INVISIBLE);
        lin_2.setVisibility(View.INVISIBLE);
        content = (TextView) findViewById(R.id.contentorder);
        category = (TextView) findViewById(R.id.category);
        Mystatus = (TextView) findViewById(R.id.status);
        handleDate = (TextView) findViewById(R.id.handleDate);
        address = (TextView) findViewById(R.id.address);
        finishWork_1 = (Button) findViewById(R.id.finish);
        finishWork_1.setOnClickListener(this);
        reservice_phone = (TextView) findViewById(R.id.reservice_phone);
        suggestion_back = (ImageView) findViewById(R.id.suggestion_back);
        suggestion_back.setOnClickListener(this);
        data = new ArrayList<>();
        data.add("信息发布");
        data.add("工人接单");
        data.add("雇主确认");
        data.add("工人完成");
        GlobalData.Myordercontent.clear();
    }

    private void getinfo() {
        if (isNetworkAvailable(this)) {
            AVUser currentUser = AVUser.getCurrentUser();
            AVQuery<AVObject> query = new AVQuery<>("MyOrderList");
            query.whereLessThan("Status", "4");
            query.whereEqualTo("WokerID", currentUser.get("username"));//通过关键字查找表单
            query.findInBackground( new FindCallback<AVObject>() {
                        @Override
                        public void done(List<AVObject> listorder, AVException e) {
                            Log.e("error", "" + e);
                            if (e == null) {
                                if(listorder!=null && listorder.size()>0){
                                if (listorder.get(0) != null) {
                                    Log.e("listorder", "" + listorder.get(0));
                                    //  AVObject avObject = listorder.get(0);

                                    String status = listorder.get(0).getString("Status");
                                    //     String status = avObject.getString("Status");
                                    if (status.equals("2")) {
                                        lin_1.setVisibility(View.VISIBLE);
                                        mView2.setVisibility(View.VISIBLE);
                                        lin_2.setVisibility(View.VISIBLE);
                                        finishWork_1.setEnabled(false);
                                        finishWork_1.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));

                                        GlobalData.Myordercontent.add(listorder.get(0));
                                        //  GlobalData.Myordercontent.add(avObject);
                                        Log.e("mydata", "" + GlobalData.Myordercontent.toString());
                                        content.setText(GlobalData.Myordercontent.get(0).get("ServiceContent").toString());
                                        category.setText(GlobalData.Myordercontent.get(0).get("RepairCategory").toString());
                                        Mystatus.setText("待完成");
                                        handleDate.setText(GlobalData.Myordercontent.get(0).get("HandleTime").toString());
                                        address.setText(GlobalData.Myordercontent.get(0).get("RealAddress").toString());

                                        reservice_phone.setText(GlobalData.Myordercontent.get(0).get("EmployerID").toString());

                                        //  int i = Integer.parseInt(GlobalData.Myordercontent.get(0).get("Status").toString());
                                        mView2.builder().pointStrings(data, 2).load();
                                    } else if (status.equals("3")) {
                                        finishWork_1.setEnabled(true);
                                        finishWork_1.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.hotgrade4));

                                        lin_1.setVisibility(View.VISIBLE);
                                        mView2.setVisibility(View.VISIBLE);
                                        lin_2.setVisibility(View.VISIBLE);
                                        GlobalData.Myordercontent.add(listorder.get(0));
                                        //  GlobalData.Myordercontent.add(avObject);
                                        Log.e("mydata", "" + GlobalData.Myordercontent.toString());
                                        content.setText(GlobalData.Myordercontent.get(0).get("ServiceContent").toString());
                                        category.setText(GlobalData.Myordercontent.get(0).get("RepairCategory").toString());
                                        Mystatus.setText("待完成");
                                        handleDate.setText(GlobalData.Myordercontent.get(0).get("HandleTime").toString());
                                        address.setText(GlobalData.Myordercontent.get(0).get("RealAddress").toString());
                                        mView2.builder().pointStrings(data, 3).load();


                                    } else {
                                        lin_1.setVisibility(View.GONE);
                                        mView2.setVisibility(View.GONE);
                                        lin_2.setVisibility(View.GONE);
                                    }
                                }
                            }
                        }
                        }
                    });

        } else {
            Toast.makeText(this, "当前无网络连接", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.suggestion_back:
                finish();
                break;
            case R.id.finish:
               // pay();调用支付宝
                ChangeOrderState();//zhij
                break;
        }
    }

    public void ChangeOrderState() {
        // 第一参数是 className,第二个参数是 objectId
        AVObject todo = AVObject.createWithoutData("MyOrderList", GlobalData.Myordercontent.get(0).getObjectId());
        Log.e("ID", GlobalData.Myordercontent.get(0).getObjectId());
        // 修改 content
        todo.put("Status", "4");
        todo.saveInBackground();   // 保存到云端
        AVUser currentUser = AVUser.getCurrentUser();
        currentUser.getCurrentUser().put("Busy", "0");
        AVUser.getCurrentUser().saveInBackground();   // 保存到云端
        mView2.builder().pointStrings(data, 4).load();
        finishWork_1.setEnabled(false);
        finishWork_1.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
        Mystatus.setText("已完成");
        GlobalData.IdG = null;
        Toast.makeText(this, "提交完成", Toast.LENGTH_SHORT).show();


    }


    public void pay() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MyOrder.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


}


